import React, {Component} from "react";
import {Card, Table, Button, Modal, message} from 'antd';
import {PAGE_SIZE} from "../../utils/constant";
import {reqRoles, reqAddRole, reqUpdateRole} from '../../api/index';
import AddForm from "../role/add-form";
import AuthForm from "./auth-form";
//import memoryUtils from "../../utils/memoryUtils";
import {formateDate} from "../../utils/dateUtils";
import {connect} from 'react-redux';
import {logout} from "../../redux/actions";
//import storageUtils from "../../utils/storageUtils";

class Role extends Component {
    state = {
        roles: [],
        role: {},
        isShowAdd: false,
        isShowAuth: false
    };

    constructor(props) {
        super(props);
        this.auth = React.createRef();
    }

    initColumns = () => {
        this.columns = [
            {
                title: '角色名称',
                dataIndex: 'name'
            },
            {
                title: '创建时间',
                dataIndex: 'create_time',
                render: (create_time) => formateDate(create_time)
            },
            {
                title: '授权时间',
                dataIndex: 'auth_time',
                render: formateDate
            },
            {
                title: '授权人',
                dataIndex: 'auth_name'
            },
        ];
    };

    onRow = (role) => {
        return {
            onClick: event => {
                this.setState({role});
            }
        };
    };

    getRoles = async () => {
        const result = await reqRoles();
        if (result.status === 0) {
            const roles = result.data;
            this.setState({roles});
        }
    };

    handleAddCancel = () => {
        this.form.resetFields();
        this.setState({isShowAdd: false});
    };

    handleUpdateCancel = () => {
        this.setState({isShowAuth: false});
    };

    addRole = () => {
        this.form.validateFields(async (err, values) => {
            if (!err) {
                this.setState({isShowAdd: false});

                const {roleName} = values;

                this.form.resetFields();
                const result = await reqAddRole(roleName);
                if (result.status === 0) {
                    message.success('创建成功');
                    const role = result.data;
                    // const roles = [...this.state.roles];
                    // roles.push(role);
                    // this.setState({roles});

                    //this.getRoles();

                    this.setState(state => ({
                        roles: [...state.roles, role]
                    }));
                } else {
                    message.error('创建失败');
                }
            }
        });
    };

    updateRole = async () => {
        // const username = memoryUtils.user.username;
        const username = this.props.user.username;
        const role = this.state.role;
        // 得到最新的menus，父组件需要取得子组件数据
        const menus = this.auth.current.getMenus();
        role.menus = menus;
        role.auth_name = username;
        role.auth_time = Date.now();
        const result = await reqUpdateRole(role);
        if (result.status === 0) {
            this.setState({isShowAuth: false});
            if (role._id === this.props.user.role_id) {
                message.success('当前用户权限发生了变化，请重新登录');
                this.props.logout();
                // memoryUtils.user = {};
                // storageUtils.removeUser();
                // this.props.history.replace('/login');
            } else {
                message.success('角色权限设置成功');
                this.setState({
                    roles: [...this.state.roles]
                });
            }
        } else {
            message.error('角色权限设置失败');
        }
    };

    componentWillMount() {
        this.initColumns();
    }

    componentDidMount() {
        this.getRoles()
    }

    render() {
        const {roles, role, isShowAdd, isShowAuth} = this.state;
        const title = (
            <span>
                <Button type='primary' onClick={()=>{this.setState({isShowAdd: true})}}>创建角色</Button>&nbsp;
                <Button type='primary' disabled={!role._id} onClick={()=>{this.setState({isShowAuth: true})}}>设置角色权限</Button>
            </span>
        );
        return (
            <Card title={title}>
                <Table
                    rowKey='_id'
                    dataSource={roles}
                    columns={this.columns}
                    bordered
                    pagination={{defaultPageSize: PAGE_SIZE, showQuickJumper: true}}
                    rowSelection={{type: 'radio', selectedRowKeys:[role._id], onSelect: (role) => {this.setState({role})}}}
                    onRow={this.onRow}
                />

                <Modal
                    title="添加角色"
                    visible={isShowAdd}
                    onOk={this.addRole}
                    onCancel={this.handleAddCancel}
                    okText="确定"
                    cancelText="取消"
                >
                    <AddForm setForm={(form)=>{this.form = form}}/>
                </Modal>

                <Modal
                    title="设置角色权限"
                    visible={isShowAuth}
                    onOk={this.updateRole}
                    onCancel={this.handleUpdateCancel}
                    okText="确定"
                    cancelText="取消"
                >
                    <AuthForm role={role} ref={this.auth}/>
                </Modal>

            </Card>
        );
    }
}

export default connect(
    state => ({user: state.user}),
    {logout}
)(Role)